import {ProColumns, ProTable} from '@ant-design/pro-components';
import {message, Modal} from 'antd';
import React, {PropsWithChildren} from 'react';
import {saveUser} from "@/services/Admin/userManage";

interface CreateModalProps {
  modalVisible: boolean;
  onSubmit: () => void;
  onCancel: () => void;
}

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: Admin.CurrentUser) => {
  const hide = message.loading('正在添加');
  try {
    await saveUser({ ...fields } as Admin.CurrentUser);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 创建数据模态框
 * @param props
 * @constructor
 */
const CreateModal: React.FC<PropsWithChildren<CreateModalProps>> = (props) => {
  const { modalVisible, onSubmit, onCancel } = props;
  /**
   * 表格列配置
   */
  const columns: ProColumns<Admin.CurrentUser>[] = [
    {
      dataIndex: 'id',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '账户',
      dataIndex: 'userAccount',
      search: false,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      search: false,
    },
    {
      title: '权限',
      dataIndex: 'isAdmin',
      search: false,
      valueType: 'select',
      valueEnum: {
        0: {
          text: '普通用户',
        },
        1: {
          text: '管理员',
        }
      }
    },
    {
      title: '账户状态',
      dataIndex: 'userStatus',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '禁用',
          status: 'Error'
        },
        1: {
          text: '启用',
          status: 'Success'
        }
      }
    },
  ];
  return (
    <Modal
      destroyOnClose
      title="新建"
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <ProTable<Admin.CurrentUser, Admin.CurrentUser>
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            onSubmit?.();
          }
        }}
        rowKey="id"
        type="form"
        columns={columns}
      />
    </Modal>
  );
};

export default CreateModal;
